import * as fs from 'fs'
import BabelCore, {PluginObj} from '@babel/core';
import {NodePath} from "@babel/traverse";
import {CallExpression, ArgumentPlaceholder, Expression, JSXNamespacedName, SpreadElement} from "@babel/types";
import * as path from "path";

let projectBasePath = process.cwd()

function readerFileCode(args: Array<Expression | SpreadElement | JSXNamespacedName | ArgumentPlaceholder>): string {
  let arg1: string = ''
  let arg2: number
  let arg3: number
  let arguments1Element = args[0];
  if (arguments1Element && arguments1Element.type === 'StringLiteral') {
    arg1 = arguments1Element.value
  } else {
    throw "第一个参数错误"
  }
  let arguments1Element2 = args[1];
  if (arguments1Element2 && arguments1Element2.type === 'NumericLiteral') {
    arg2 = arguments1Element2.value
  }
  let arguments1Element3 = args[2];
  if (arguments1Element3 && arguments1Element3.type === 'NumericLiteral') {
    arg3 = arguments1Element3.value
  }
  let fullPath = projectBasePath + path.sep + arg1
  let fileContent = ''
  try {
    fileContent = fs.readFileSync(fullPath, {encoding: 'utf8'})
  } catch (e) {
    fileContent = fullPath + '：文件没有找到'
  }
  return fileContent.split('\n').slice(arg2, arg3).join('\n')
}

function replaceWith(path: NodePath<CallExpression>, t: typeof BabelCore.types) {
  let node = path.node
  try {
    let code = readerFileCode(node.arguments)
    path.replaceWith(t.stringLiteral(code))
  } catch (e){
    // 重新排队
    path.requeue()
  }
}

// 这个插件处理 window.__readerFileCode__ 这个函数，替换成字符串
export default function (babel: typeof BabelCore): PluginObj {
  let t = babel.types
  return {
    name: "babel-plugin-readerFileCode",
    visitor: {
      CallExpression(path: NodePath<CallExpression>, state) {
        let node = path.node
        let callee = node.callee;
        if (callee.type === 'MemberExpression') {
          const property = callee.property;
          if (property.type === 'Identifier') {
            const name1 = property.name;
            if (name1 === '__readerFileCode__') {
              // 这里就找到了 window.__readerFileCode__
              replaceWith(path, t)
            }
          }
        } else if (callee.type === 'Identifier') {
          if (callee.name === '__readerFileCode__') {
            // 找到 __readerFileCode__
            replaceWith(path, t)
          }
        }
      },
    }
  };
}









